#include <string>
#include <iostream>
#include <functional>
#include "include/muduo/net/TcpServer.h"
#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/net/TcpClient.h"
#include "include/muduo/base/CountDownLatch.h"
class TranslateClient
{
public:
    TranslateClient(const std::string &serverip, const int serverport)
        : _client(_loopthread.startLoop(), muduo::net::InetAddress(serverip, serverport), "TranslateClient"),
          _latch(1)
    {
        _client.setConnectionCallback(bind(&TranslateClient::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(bind(&TranslateClient::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    // 阻塞连接，直到连接成功
    void connect()
    {
        _client.connect();
        _latch.wait(); // 阻塞
    }

    bool send(const std::string &message)
    {
        if (_conn->connected())
        {
            _conn->send(message);
            return true;
        }
        return false;
    }

private:
    // 建立连接和断开才调用，唤醒阻塞
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            _latch.countDown();
            _conn = conn;
        }
        else
        {
            _conn.reset();
            std::cout << "连接断开" << std::endl;
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buffer, muduo::Timestamp)
    {
        // 处理业务->将收到的数据打印
        std::string inbuffer = buffer->retrieveAllAsString();
        std::cout << "翻译后:" << inbuffer << std::endl;
    }

private:
        muduo::CountDownLatch _latch;
        muduo::net::EventLoopThread _loopthread;
        muduo::net::TcpClient _client;
        muduo::net::TcpConnectionPtr _conn;
};

int main()
{
    std::unique_ptr<TranslateClient> client = std::make_unique<TranslateClient>("127.0.0.1", 8080);
    client->connect();
    while (1)
    {
        std::string message;
        std::cin >> message;
        client->send(message);
    }
    return 0;
}
